#import "SMRShadowRatingView.h"
#import "SMRShadowRatingCell.h"


#pragma mark -
@interface SMRShadowRatingView ()
@property (nonatomic, assign) BOOL overlayInnerRectNeedsUpdate;
-(void)setOverlayInnerRect:(NSRect)innerRect;
-(NSRect)overlayInnerRect;
@end


#pragma mark -
@interface SMRShadowRatingView (SMRShadowRatingViewPrivateMethods)
-(void)shadowRatingViewCommonInit_;
-(SMRShadowRatingCell *)shadowCell_;
@end


#pragma mark -
@implementation SMRShadowRatingView

@synthesize overlayInnerRectNeedsUpdate;
@synthesize shadowView;


#pragma mark -
#pragma mark Initialization

-(id)initWithFrame:(NSRect)frameRect {
	if (!(self = [super initWithFrame:frameRect]))
		return nil;
	[self shadowRatingViewCommonInit_];
	return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
	if (!(self = [super initWithCoder:aDecoder]))
		return nil;
	[self shadowRatingViewCommonInit_];
	return self;
}

-(void)shadowRatingViewCommonInit_ {
	[self setShadowView:[[SMROverlayShadowEffectView alloc] initWithFrame:NSZeroRect]];
	[[self shadowView] setBorderPadding:4.0f];
}


#pragma mark -
#pragma mark Accessors

+(Class)cellClass {
	return [SMRShadowRatingCell class];
}

-(void)setEditingColor:(NSColor *)aColor {
	[[self shadowCell_] setRatingColor:aColor];
}

-(NSColor *)editingColor {
	return [[self shadowCell_] ratingColor];
}

-(NSRect)overlayInnerRect {
	return [[self shadowCell_] overlayInnerRect];
}

-(void)setOverlayInnerRect:(NSRect)innerRect {
	[[self shadowCell_] setOverlayInnerRect:innerRect];
}


#pragma mark -
#pragma mark Overrides

-(void)viewWillDraw {
	if ([self overlayInnerRectNeedsUpdate])
		[self updateOverlay];
}

-(BOOL)becomeFirstResponder {
	[self showEditModeBezel];
	[[self shadowCell_] setEditing:YES];
	return [super becomeFirstResponder];
}

-(BOOL)resignFirstResponder {
	[self hideEditModeBezel];
	[[self shadowCell_] setEditing:NO];
	return [super resignFirstResponder];
}


#pragma mark -
#pragma mark Overlay support

-(void)showEditModeBezel {
	[self setOverlayInnerRectNeedsUpdate:YES];
	[self setNeedsDisplay:YES];
}

-(void)hideEditModeBezel {
	[[self shadowView] removeFromSuperview];
	[self setNeedsDisplay:YES];
}

-(NSRect)overlayRectForRect:(NSRect)bounds {
	NSSize minSize = [[self cell] cellSizeForBounds:bounds];
	NSRect overlayRect = bounds;
	overlayRect.size = minSize;
	return overlayRect;
}

-(void)updateOverlay {
	NSRect overlayRect = [self overlayRectForRect:[self visibleRect]];
	[self setOverlayInnerRect:overlayRect];
	[self setOverlayInnerRectNeedsUpdate:NO];
	
	if  ([[self shadowView] superview]) 
		[[self shadowView] updateOverlayRect:overlayRect];
	else 
		[[self shadowView] setOverlayRect:overlayRect inView:self];
}


#pragma mark -
#pragma mark Private

-(SMRShadowRatingCell *)shadowCell_ {
	return (SMRShadowRatingCell *)[self cell];
}

@end
